package framework;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.openems.entity.Entity;
import org.openems.entity.Key;

public class ClientManager implements Command {
	private Map<Key, List<EntityStoreListener>> listeners = new HashMap<Key, List<EntityStoreListener>>();
	protected Accessor accessor;

	protected void fireChangeEvent(Map<Key, Entity> changedValues) {
		for (Key key : changedValues.keySet()) {
			List<EntityStoreListener> list = listeners.get(key);
	
			if (list == null) {
				continue;
			}
			
			Entity entity = changedValues.get(key);
			for (EntityStoreListener listener : list) {
				listener.valueChanged(entity);
			}
		}
	}

	/* (non-Javadoc)
	 * @see framework.ClinetManager#addListener(framework.EntityStoreListener, org.openems.entity.Key)
	 */
	public void addListener(EntityStoreListener entityStoreListener, Key key) {
		if (!listeners.containsKey(key)) {
			listeners.put(key, new ArrayList<EntityStoreListener>());
		}
		List<EntityStoreListener> list = listeners.get(key);
		list.add(entityStoreListener);
	}

	/* (non-Javadoc)
	 * @see framework.ClinetManager#removeListener(framework.EntityStoreListener)
	 */
	public void removeListener(EntityStoreListener entityStoreListener) {
		for (Key key : this.listeners.keySet()) {
			if (listeners.get(key).contains(entityStoreListener)) {
				listeners.get(key).remove(entityStoreListener);
			}
		}
	}
	
	public ClientManager(Accessor accessor) {
		this.accessor = accessor;
	}
	
	@Override
	public void execute(List<Key> changedKey, Key key) {
		//createRunnable(changedKey).run();
		fireChangeEvents(changedKey);
	}

	void fireChangeEvents(final List<Key> changedKey) {
		Map<Key, Entity> changedValues = new HashMap<Key, Entity>();
		for (Key key : changedKey) {
			changedValues.put(key, accessor.get(key));
		}
		fireChangeEvent(changedValues);
	}

}